//获取2位小数，不四舍五入
function Round2(temp) {
    var value = temp.toFixed(2);
    return value;
}

$(function () {

    var btn = $("#calcSubmit"),
        reset = $("#reset"),
        timeType = $('#timeType'),
        method = $("#repayMethod"),
        moneyInput = $("#amount"),
        aprNum = $("#apr"),
        timeInput = $("#time"),
        table = $("#incomeTable"),
        investAmount = $("#investAmount"),
        interest = $("#interest"),
        hideDiv = $(".resultTab"),
        firstMonth = $("#firstMonth"),
        secondMonth = $("#secondMonth");

    //计算
    btn.click(function () {
        calculate();
    });

    //重置
    reset.click(function () {
        moneyInput.val("");
        aprNum.val("");
        timeInput.val("");
        method.val(1);
        timeType.val(1);
    });


    blurInputInt(moneyInput);
    blurInputFloat(aprNum);
    blurInputInt(timeInput);
    blurInputInt(firstMonth);
    blurInputInt(secondMonth);

    method.change(function () {
        var unitVal = $(this).val();
        $(this).children("option[value=" + unitVal + "]").prop('selected', true).siblings("option").prop('selected', false);
        var option = '<option value="2">天</option><option value="1">月</option>';
        if (unitVal == 3 || unitVal == 5) {
            timeType.val(1);
            timeType.children("option[value='2']").remove();
        } else {
            timeType.html(option);
            timeType.val(2);
        }

        if (unitVal == 5) {
            $("#type5").show();
            $("#typeOther").hide();
        } else {
            $("#type5").hide();
            $("#typeOther").show();
        }
    });

    //计算
    function calculate() {
        var amount = parseFloat(moneyInput.val()); //获取借款金额
        var apr = parseFloat(aprNum.val()); //获取年利率
        var time = parseInt(timeInput.val()); //获取借款期限
        var month1 = parseInt(firstMonth.val()); //获取还息月期限
        var month2 = parseInt(secondMonth.val()); //获取还本月期限
        if (!verification(amount, apr, time, month1, month2)) {
            return false;
        }
        var time_type = timeType.val();
        var rate = apr / (100 * 12);
        var text = method.val();

        //表头
        var str = "<tr><th>期数</th><th>回购本息（元）</th><th>回购本金（元）</th><th>回购利息（元）</th><th>剩余本息(元)</th></tr>";
        if (text == 1 && time_type == 1) {
            var mon = 0;
            for (var j = 1; j < time + 1; j++) {
                if (j == time) {
                    mon = amount;
                }
                str += "<tr>";
                str += "<td>" + (j) + "</td>"//期数
                str += "<td>" + Round2(amount * rate + mon) + " 元</td>"; //每期还款本息
                str += "<td>" + Round2(mon) + " 元</td>"; //每期还款本金
                str += "<td>" + Round2(amount * rate) + " 元</td>"; //利息
                str += "<td>" + Round2(amount + amount * rate * time - amount * rate * parseInt(j) - mon) + " 元</td>"; //余额
                str += "</tr>";
            }
            investAmount.html(Round2(amount));
            interest.html(Round2(amount * rate * time));
        }
        else if (text == 1 && time_type == 2) {

            var inss = 0;
            var time_s = Math.ceil(time / 30); //期数
            var last_time = (time % 30 === 0 && time !== 0 ? 30 : time % 30);
            for (var j = 1; j < time_s + 1; j++) {
                str += "<tr>";
                str += "<td>" + (j) + "</td>"; //期数
                if (j == 1) {	//第一期，按天计算利息
                    inss += parseFloat(Round2(amount * last_time * (rate / 30)));
                    if (j == time_s) {
                        str += "<td>" + Round2(amount + inss) + " 元</td>"; //每期还款本息
                        str += "<td>" + Round2(0.00) + " 元</td>"; //每期还款本金
                        str += "<td>" + Round2(inss) + " 元</td>"; //利息
                        str += "<td>0 元</td>"; //余额
                    } else {
                        str += "<td>" + Round2(inss) + " 元</td>"; //每期还款本息
                        str += "<td>" + Round2(0.00) + " 元</td>"; //每期还款本金
                        str += "<td>" + Round2(inss) + " 元</td>"; //利息
                        str += "<td>" + Round2(amount + amount * (rate * (time_s - 1))) + " 元</td>"; //余额
                    }
                } else if (j == time_s) {
                    inss += parseFloat(Round2(amount * rate));
                    str += "<td>" + Round2(amount + amount * rate) + " 元</td>"; //每期还款利息
                    str += "<td>" + Round2(amount) + " 元</td>"; //每期还款本金
                    str += "<td>" + Round2(amount * rate) + " 元</td>"; //利息
                    str += "<td>0 元</td>"; //余额
                }
                else {
                    inss += parseFloat(Round2(amount * rate));
                    str += "<td>" + Round2(amount * rate) + " 元</td>"; //每期还款利息
                    str += "<td>" + Round2(0.00) + " 元</td>"; //每期还款本金
                    str += "<td>" + Round2(amount * rate) + " 元</td>"; //利息
                    str += "<td>" + Round2(amount + amount * rate * (time_s - j)) + " 元</td>"; //余额
                }
                // str += "<td>--</td>"; //余额
                str += "</tr>";
            }
            investAmount.html(Round2(amount));
            interest.html(Round2(inss));
            table.html(str); //将表格的内容填充到div中
            hideDiv.show();
        }
        if (text == 2 && time_type == 1) {
            str += "<tr>";
            str += "<td>" + 1 + "</td>";//期数
            str += "<td>" + Round2((amount * rate * time) + amount) + " 元</td>";
            str += "<td>" + Round2(amount) + " 元</td>";
            str += "<td>" + Round2(amount * rate * time) + " 元</td>"; //利息
            str += "<td>" + "0 元</td>"; //余额
            str += "</tr>";
            table.html(str); //将表格的内容填充到div中
            investAmount.html(Round2(amount));
            interest.html(Round2(amount * rate * time));
        }
        else if (text == 2 && time_type == 2) {
            str += "<tr>";
            str += "<td>" + 1 + "</td>";//期数
            str += "<td>" + Round2((amount * ((apr / 100) * (time / 360))) + amount) + " 元</td>";
            str += "<td>" + Round2(amount) + " 元</td>";
            str += "<td>" + Round2(amount * ((apr / 100) * (time / 360))) + " 元</td>"; //利息
            str += "<td>" + "0 元</td>"; //余额
            str += "</tr>";
            investAmount.html(Round2(amount));
            interest.html(Round2(amount * ((apr / 100) * (time / 360))));
        }
        if (text == 3) {
            str += "<tr><td>申购时付息</td>";//期数
            str += "<td>" + Round2(amount * rate * time) + " 元</td>"; //	先还利息
            str += "<td>" + 0 + " 元</td>"; //每期还款本金
            str += "<td>" + Round2(amount * rate * time) + " 元</td>"; //利息
            str += "<td>" + Round2(amount) + " 元</td>"; //余额
            str += "</tr>";
            str += "<tr ><td>1</td>";//期数
            str += "<td>" + Round2(amount) + " 元</td>"; //	到期还款本
            str += "<td>" + Round2(amount) + " 元</td>"; //到期还款本
            str += "<td>" + 0 + " 元</td>"; //利息
            str += "<td>" + 0 + " 元</td>"; //余额
            str += "</tr>";
            investAmount.html(Round2(amount));
            interest.html(Round2(amount * rate * time));
        }
        if (text == 4 && time_type == 1) {
            var ins = 0;
            for (var j = 1; j < time + 1; j++) {
                str += "<tr class=\"tool_tr2\">";
                str += "<td>" + (j) + "</td>";//期数

                str += "<td>" + Round2((amount / time) + (amount - (amount / time) * (j - 1)) * rate) + " 元</td>"; //每期还款本息

                str += "<td>" + Round2(amount / time) + " 元</td>"; //每期还款本金
                str += "<td>" + Round2((amount - (amount / time) * (j - 1)) * rate) + " 元</td>"; //利息
                str += "<td>" + Round2(amount - (amount / time) * j) + " 元</td>"; //余额
                str += "</tr>";
                ins += (amount - (amount / time) * (j - 1)) * rate;	//累计利息
            }
            str += "</table>";
            investAmount.html(Round2(amount));
            interest.html(Round2(ins));
        }
        else if (text == 4 && time_type == 2) {
            var ins = 0 , total = 0;
            var times = Math.ceil(time / 30); //期数
            var lastTime = (time % 30 === 0 && time !== 0 ? 30 : time % 30);
            for (var m = 1; m < times + 1; m++) {
                m == 1 ? total += amount * lastTime * (rate / 30) : total += ((amount - (amount / times) * (m - 1)) * rate);
            }
            for (var j = 1; j < times + 1; j++) {
                str += "<tr>";
                str += "<td>" + (j) + "</td>";//期数
                if (j == 1) {	//第一期，按天计算利息
                    ins += amount * lastTime * (rate / 30);
                    str += "<td>" + Round2(amount / times + ins) + " 元</td>"; //每期还款本息
                    str += "<td>" + Round2(amount / times) + " 元</td>"; //每期还款本金
                    str += "<td>" + Round2(ins) + " 元</td>"; //利息
                    str += "<td>" + Round2((amount - amount / times) + ( total - ins)) +" 元</td>"; //余额
                }
                else {
                    ins += ((amount - (amount / times) * (j - 1)) * rate);
                    str += "<td>" + Round2((amount / times) + (amount - (amount / times) * (j - 1)) * rate) + " 元</td>"; //每期还款利息
                    str += "<td>" + Round2(amount / times) + " 元</td>"; //每期还款本金
                    str += "<td>" + Round2((amount - (amount / times) * (j - 1)) * rate) + " 元</td>"; //利息
                    if(j == times) {
                        str += "<td>0 元</td>"; //余额
                    }else{
                        str += "<td>" + Round2((amount - (amount / times * j)) + ( total - ins)) +" 元</td>"; //余额
                    }
                }
                str += "</tr>";

            }
            investAmount.html(Round2(amount));
            interest.html(Round2(ins));
        }
        if (text == 5 && time_type == 1) {
            var total = 0 , inss = 0;
            // var month_apr = parseFloat(apr / (12 * 100));
            var first_interest = parseFloat(amount * rate);
            var monthCapital = amount / month2;
            // 先计算总利息
            for (var sm = 1; sm <= month1; sm++) {
                total += first_interest;	//累计利息
            }
            for (var km = 1; km <= month2; km++) {
                var second_interest = (amount - monthCapital * (km - 1)) * rate;
                total += second_interest;	//总
            }

            for (var m = 1; m <= month1; m++) {
                inss += first_interest;	//累计利息
                str += "<tr class=\"tool_tr2\">";
                str += "<td>" + (m) + "</td>";//期数
                str += "<td>" + Round2(first_interest) + " 元</td>"; //每期还款本息  => 本金 0
                str += "<td>0.00 元</td>"; //每期还款本金
                str += "<td>" + Round2(first_interest) + " 元</td>"; //利息
                str += "<td>" + Round2(amount + (total - first_interest * m)) + " 元</td>"; //余额
                str += "</tr>";
            }

            for (var k = 1; k <= month2; k++) {
                var second_interest = (amount - monthCapital * (k - 1)) * rate;
                inss += second_interest;
                str += "<tr class=\"tool_tr2\">";
                str += "<td>" + (k + month1) + "</td>";//期数
                str += "<td>" + Round2(monthCapital + second_interest) + " 元</td>"; //每期还款本息
                str += "<td>" + Round2(monthCapital) +" 元</td>"; //每期还款本金
                str += "<td>" + Round2(second_interest) + " 元</td>"; //利息
                if(k == month2){
                    str += "<td>0 元</td>"; //余额
                }else{
                    str += "<td>" + Round2((amount - monthCapital * k) + (total - inss)) + " 元</td>"; //余额
                }
                str += "</tr>";
            }
            investAmount.html(Round2(amount + inss));
            interest.html(Round2(inss));
        }
        table.html(str); //将表格的内容填充到div中
        hideDiv.show();
    }

    /**
     * 验证
     */
    function verification(money, rate, time, month1, month2) {

        var r2 = /^[1-9]\d*$/;
        // var r = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
        var r = /^\d+(?:\.\d{1,2})?$/;
        if (!r.test(money)) {
            layer.alert("投资金额输入有误，请重新输入！"), function (index) {
                layer.close(index);
                moneyInput.focus();
            };
            return false;
        }
        if (!r.test(rate)) {
            layer.alert("年化利率输入有误，请重新输入！", function (index) {
                layer.close(index);
                aprNum.focus();
            });
            return false;
        }
        if (method.val() == 5) {
            if (!r2.test(month1)) {
                layer.alert("还息月输入有误，请重新输入！", function (index) {
                    layer.close(index);
                    firstMonth.focus();
                });
                return false;
            }
            if (!r2.test(month2)) {
                layer.alert("还本月输入有误，请重新输入！", function (index) {
                    layer.close(index);
                    secondMonth.focus();
                });
                return false;
            }
        } else {
            if (!r2.test(time)) {
                layer.alert("借款期限输入有误，请重新输入！", function (index) {
                    layer.close(index);
                    timeInput.focus();
                });
                return false;
            }
        }
        return true;
    }

    function blurInputFloat(id) {
        $(id).blur(function () {
            var val = $(this).val();
            if (val.length === 0 || isNaN(val)) {
                $(this).val('');
            } else {
                $(this).val(parseFloat(val).toFixed(2));
            }
        });
    }

    function blurInputInt(id) {
        $(id).blur(function () {
            var val = $(this).val();
            if (val.length === 0 || isNaN(val)) {
                $(this).val('');
            } else {
                $(this).val(parseInt(val));
            }
        });
    }

});
